﻿using System;
using System.Diagnostics;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;

namespace Sharp.Infrastructure.Wcf
{
    [DebuggerStepThrough]
    public class ContextReceiver : ICallContextInitializer
    {
        public void AfterInvoke(object correlationState) { }
        public object BeforeInvoke(InstanceContext instanceContext, IClientChannel channel, Message message)
        {
            var context = message.Headers.GetHeader<ContactContext>(ContactContext.ContextHeaderLocalName, ContactContext.ContextHeaderNamespace);

            ContactContext.Current = context;
            if (ContactContext.Current != null && ContactContext.Current.UserId != Guid.Empty)
            {
                return ContactContext.Current;
            }
            else
            {
                if (message.Headers.Action.Contains("UserService"))
                {
                    return ContactContext.Current;
                }
                else
                {
                    throw new Exception("用户未登录");
                }
            }
        }
    }
}
